package com.jiufengxinxi.ts.common.utils;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class StreamUtil {


    public static int copy(InputStream input, OutputStream output)
            throws IOException
    {

        long count = copyLarge(input, output);
        if (count > 2147483647L) {
            return -1;
        }
        return (int)count;
    }

    public static long copyLarge(InputStream input, OutputStream output)
            throws IOException
    {
        byte[] buffer = new byte[1024];
        long count = 0L;
        int n = 0;
        while (input.available()>0) {
            n = input.read(buffer);
            if(n<0) {
            	break;
            }
            output.write(buffer);
            count += n;
        }
        return count;
    }
    
    
    public static int copy(InputStream input, OutputStream output,int minlen,int timeoutMillis)
            throws IOException
    {
        long count = copyLarge(input, output,minlen,timeoutMillis);
        if (count > 2147483647L) {
            return -1;
        }
        return (int)count;
    }

    public static long copyLarge(InputStream inputStream, OutputStream output,int minlen,int timeoutMillis)
            throws IOException
    {
        byte[] buffer = new byte[minlen];
        long count = 0L;
        int n = 0;
        int responseWaitTime = 0;
        
        while (inputStream.available() < minlen && responseWaitTime <timeoutMillis)
        {
            try {
				Thread.sleep(10);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
            responseWaitTime+=10;
        }
        if (inputStream.available() <= 0)
        {
            throw new IOException("Timeout");
        }
        
        while (inputStream.available()>0 && (n = inputStream.read(buffer))>=0) {
            output.write(buffer);
            count += n;
        }
        return count;
    }

}
